<template>
  <div>
    <el-row v-for="(medical,index) in list" :key="index">
      <div style="display: flex;align-items: center;justify-content: space-between">
        <el-col :span="3">
          <div v-if="index>0 &&!medical.close && !list[index-1].open">
            <el-select v-if="!medical.close" v-model="medical.method" @change="change"
                       placeholder="请选择">
              <el-option
                v-for="item in methods"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="18">
          <el-button v-if="medical.open"
                     style="font-size: 16px;border:1px solid #EEE;padding: 5px"
                     type="text">(
          </el-button>
          <el-button v-if="medical.close"
                     style="font-size: 16px;border:1px solid #EEE;padding: 5px"
                     type="text">)
          </el-button>
          <div v-if="medical.close===false&&medical.open===false"
               style="display: flex;align-items: center;justify-content: space-between">
            <el-row style="display: flex;justify-content: space-between">
              <el-select style="max-width: 180px;min-width: 180px;" @change="changeTable($event, medical)"
                         v-model="medical.tableName">
                <el-option v-for="item in moreList.tableList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
              <el-select style="max-width: 180px;min-width: 180px;" v-model="medical.field"
                         @change="changeField(medical,$event)">
                <el-option v-for="item in fieldList"
                           :key="item.fieldName"
                           :label="item.name"
                           :value="item.fieldName"></el-option>
              </el-select>
              <!--              <el-dict code="ADVANCE_SEARCH_FIELDS" v-model="medical.field" :custom-style="{width: '180px'}"-->
              <!--                       @change="changeAdvanceSearchFields(medical, $event)" placeholder="请选择字段"></el-dict>-->
              <!--              <div style="max-width: 110px;min-width: 110px;">-->
              <!--                <el-select v-model="medical.condition" @change="changeCondition(medical, $event)"-->
              <!--                           placeholder="请选择">-->
              <!--                  <el-option-->
              <!--                    v-for="item in medical.conditions"-->
              <!--                    :key="medical.fieldName + item"-->
              <!--                    :label="item"-->
              <!--                    :value="item">-->
              <!--                  </el-option>-->
              <!--                </el-select>-->
              <!--              </div>-->
              <!--              <el-date-picker v-model="medical.value" v-if="medical.fieldObj.type ==='daterange'" @change="change"-->
              <!--                              type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"-->
              <!--                              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>-->
              <!--              <div style="display: flex" v-else-if="medical.fieldObj.type ==='range'">-->
              <!--                <el-input v-model="medical.value[0]" placeholder="开始值" @change="change"></el-input>-->
              <!--                <el-input v-model="medical.value[1]" placeholder="结束值" @change="change"></el-input>-->
              <!--              </div>-->
              <!--              <advance-selector v-else-if="medical.fieldObj.type==='selector'" :list="medical.list"-->
              <!--                                :valid="!medical.value"-->
              <!--                                :multiple="medical.condition&&medical.condition.indexOf('in')>-1"-->
              <!--                                v-model="medical.value"-->
              <!--                                @change="changeSelector(medical, $event)"></advance-selector>-->
              <el-input v-model="medical.value" placeholder="请输入" @change="change"></el-input>
            </el-row>
          </div>
        </el-col>
        <el-col :span="3" style="padding-left: 10px">
          <el-button style="color: red" v-if="!medical.close&&index!==0&&!medical.open" type="text"
                     @click="deleteMethod(index)">-
          </el-button>
          <el-button type="text" v-if="!medical.open" @click="addSimple(index,medical)"> +</el-button>
          <el-button v-if="!medical.child && !medical.open" type="text" @click="addMethod(index)">(+)
          </el-button>
        </el-col>
      </div>
    </el-row>
  </div>
</template>

<script>
import advanceSelector from './advance-selector'

const FIELD_TYPE = {
  'single': ['=', '!=', '>', '<', '>=', '<=', 'like'],
  'range': ['between'],
  'daterange': ['between'],
  'selector': ['=', '!=', 'in', 'not in']
}
export default {
  name: 'advance-field-search',
  componentName: 'advanceFieldSearch',
  components: {advanceSelector},
  props: {
    prefix: {
      type: [String],
      default: ''
    },
    value: {
      type: [Array, String],
      default() {
        return [{
          method: 'and',
          value: '',
          condition: '=',
          fieldName: '',
          open: false,
          close: false,
          field: '',
          fieldObj: {},
          list: []
        }]
      }
    },
    moreList: {
      type: [Object],
      default() {
        return []
      }
    },
    placeholder: {
      type: [String],
      default: '请选择'
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) {
          this.list = newVal
        }
      }
    }
  },
  data() {
    return {
      methods: ['and', 'or'],
      defaultConditions: ['=', '!=', '>', '<', '>=', '<=', 'in', 'not in', 'between', 'like'],
      defaultField: {
        method: 'and',
        value: '',
        condition: 'like',
        fieldName: '',
        open: false,
        close: false,
        field: '',
        fieldObj: {},
        list: []
      },
      list: [],
      fieldList: []
    }
  },
  created() {
    this.defaultField.conditions = {...this.defaultConditions}
    this.list = [{...this.defaultField}]
    this.change()
  },
  methods: {
    changeTable(val, medical) {
      console.log(medical)
      this.fieldList = this.moreList.tableColumns[val]
      medical.field = ''
      console.log(this.fieldList)
      this.change()
    },
    changeField(medical, val) {
      medical.fieldName = val
      this.change()
    },
    changeAdvanceSearchFields(medical, val) {
      if (!val) {
        return
      }
      medical.value = ''
      medical.fieldObj = JSON.parse(val)
      medical.fieldName = medical.fieldObj.field
      // if (medical.fieldObj && medical.fieldObj.type.indexOf('range') > -1) {
      //   medical.condition = 'between'
      // } else {
      //   medical.condition = '='
      // }
      if (medical.fieldObj.type.indexOf('range') > -1) {
        medical.value = []
      }
      medical.conditions = FIELD_TYPE[medical.fieldObj.type]
      medical.condition = medical.conditions[0]
      if (medical.fieldObj.type === 'selector') {
        this.$nextTick(() => {
          this.$http({
            url: medical.fieldObj.url,
            method: 'post'
          }).then(({data}) => {
            medical.list = [{label: '请选择', value: ''}]
            if (data && data.code === 0) {
              data.list.forEach(({label, value}) => {
                medical.list.push({label, value})
              })
              console.log(medical)
              this.$forceUpdate()
            }
          })
        })
      } else {
        console.log(medical)
      }
      this.change()
    },
    addSimple(index, medical) {
      this.list.splice(index + 1, 0, {
        ...this.defaultField,
        child: medical.child
      })
      this.change()
    },
    addMethod(index) {
      this.list.splice(index + 1, 0, {
        ...this.defaultField,
        open: true
      })
      this.list.splice(index + 2, 0, {
        ...this.defaultField,
        child: true
      })
      this.list.splice(index + 3, 0, {
        ...this.defaultField,
        close: true
      })
      this.change()
    },
    deleteMethod(index) {
      const i = index
      if (i > 0 && i < this.list.length - 1 && this.list[i - 1].open && this.list[i + 1].close) {
        this.list.splice(i - 1, 3)
      } else {
        this.list.splice(i, 1)
      }
      this.change()
    },
    changeSelector(medical, val) {
      medical.value = val
      console.log('选择值：{}', this.list)
      this.change()
    },
    changeCondition(medical, val) {
      medical.value = ''
      if (medical.condition.indexOf('in') > -1) {
        medical.value = []
      }
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      this.change()
    },
    change() {
      console.log(JSON.stringify(this.list))
      this.$emit('input', this.list)
      this.$emit('change', this.toSql())
    },
    toSql() {
      let sql = ''
      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i]
        if (item.open) {
          sql += ' ' + item.method + ' ('
        }
        // 组装条件 START
        if (!item.open && !item.close && item.method && !item.child && item.fieldName && item.value) {
          if (i === 0) {
            sql = ''
          } else {
            sql += ' ' + item.method
          }
          sql += ' ' + this.prefix + this.moreList.tableColumns.COLUMN_MAP[item.fieldName] + ' ' + item.condition + this.buildValue(item)
        } else if (item.child && item.fieldName && item.value) {
          if (sql.substring(sql.length - 1, sql.length) !== '(') {
            sql = sql + ' ' + item.method
          }
          sql += ' ' + this.prefix + this.moreList.tableColumns.COLUMN_MAP[item.fieldName] + ' ' + item.condition + this.buildValue(item)
        }
        // 组装条件 END
        if (item.close) {
          sql += ') '
        }
      }
      console.log(JSON.stringify(sql))
      return sql
    },
    buildValue(item) {
      switch (typeof item.value) {
        case 'object': {
          if (item.condition.indexOf('in') > -1) {
            return ' (' + item.value.map(p => '\'' + p + '\'').join(' , ') + ') '
          }
          return ' ' + item.value.map(p => '\'' + p + '\'').join(' and ')
        }
        default: {
          if (item.condition === 'like') {
            return ' \'%' + item.value + '%\''
          }
          return ' \'' + item.value + '\''
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.required {
  input {
    background-color: #EB6709;
  }
}
</style>
